import Taro, { Component } from '@tarojs/taro'
import {View, Image, Text, ScrollView} from '@tarojs/components'
import {AtButton, AtIcon, AtSwipeAction} from 'taro-ui'
import { connect } from '@tarojs/redux'
import "taro-ui/dist/weapp/components/swipe-action/index.scss";

import {
  loadCart,
  asyncLoadCart,
  resetCart,
  asyncAddCartAction,
  asyncReduceCartAction,
  asyncRemoveCartAction,
  setCartBadge,
  asyncLoadOffer // 加载推荐商品列表
} from '../../actions/cart'
import './index.styl'
import emptyCartPng from '../../assets/images/cart/empty-cart.png'
import checkPng from '../../assets/images/cart/checked.png'
import uncheckPng from '../../assets/images/cart/uncheck.png'
import  CartGoodItem  from "../../components/cartGoodItem/index"
import {GoodItem} from '../../components/homeGoodItem/goodItem'
import { jumpUrl } from '../../utils/router'

@connect(({ cart, shop }) => ({
  cart, shop
}), (dispatch) => ({
  // 加载购物车数据
  onAsyncLoadCart () {
    return dispatch(asyncLoadCart())
  },
  // 重置购物车
  onResetCart () {
    dispatch(resetCart())
  },
  // 增加数量
  onAddCart (shop_id, product_id, product_num) {
    dispatch(asyncAddCartAction(shop_id, product_id, product_num))
  },
  // 减少数量
  onReduceCart (product_id, product_num) {
    dispatch(asyncReduceCartAction(product_id, product_num))
  },
  // 删除商品
  onRemoveCartAction(cart_id) {
    dispatch(asyncRemoveCartAction(cart_id))
  },
  // 加载购物车tabber数量
  onSetCartBadge () {
    dispatch(setCartBadge())
  },
  // 切换选中
  onChangeSelect (list) {
    dispatch(loadCart({list}))
  },
  // 为结算设置配送方式
  onSetDeliveryMethod (method) {
    dispatch(loadCart({deliveryMethod: method}))
  },
  // 加载推荐商品列表
  onAsyncLoadOffer() {
    console.log('dispatch 加载推荐商品')
    dispatch(asyncLoadOffer())
  }
}))
class Cart extends Component {
  constructor () {
    super(...arguments)
    this.state = {
      deliveryMethod: 'shop' // 配送方式 shop / user 店家或者买家自取
    }
  }
    config = {
    navigationBarTitleText: '购物车'
  }

  // 设置配送方式
  setDeliveryMethod (method) {
    this.setState({
      deliveryMethod: method
    })
  }
  // 跳转
  jumpTo (url) {
    jumpUrl(url, {method: 'navigateTo'})
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  // 商品操作 (删除)
  handleItemClick (item) {
    console.log(item)
    this.props.onRemoveCartAction(item.id)
    setTimeout(() => {
      this.props.onSetCartBadge()
    }, 300)
  }

  // 数量改变
  handleChange (product_id, shop_id, product_num) {
    const {list} = this.props.cart
    const product = list.find(good => good.product_id === product_id)
    if (product.product_num === product_num) return
    const type = product.product_num > product_num ? 'reduce' : 'add'
    switch (type) {
      case 'reduce':
        this.props.onReduceCart(product_id, product_num)
            break
      case 'add':
        this.props.onAddCart(shop_id, product_id, product_num)
        break
    }
  }

  // 选中改变
  // TODO 如何在刷新购物车后保持未选中
  handleSelect (product_id) {
    const {list} = this.props.cart
    const newList = JSON.parse(JSON.stringify(list))
    const product = newList.find(good => good.product_id === product_id)
    product.selected = !product.selected
    this.props.onChangeSelect(newList)
  }

  // 结算
  goSettle () {
    const {list} = this.props.cart
    const selected = list.filter(item => item.selected)
    if (selected.length === 0) {
      Taro.showToast({
        title: '没有选中商品',
        icon: 'none'
      })
      return
    }
    const {min_orderamount} = this.props.shop
    const {deliveryMethod} = this.state
    const total = this.props.cart.list
      .filter(product => product.selected === true)
      .reduce((sum, product) => sum + product.product_num * product.product.sale_price, 0) || 0
    // 为结算设置配送方式
    this.props.onSetDeliveryMethod(deliveryMethod)
    // 如果总价达不到起送的金额，提示用户
    // if (deliveryMethod === 'shop' && min_orderamount && min_orderamount > total) {
    //   Taro.showToast({
    //     title: '订单金额不满足起送金额',
    //     icon: 'none'
    //   })
    //   return
    // } else {
    //   this.jumpTo('/pages/cart/settle?type=1')
    // }
    this.jumpTo('/pages/cart/settle?type=1')
  }

  // 跳转首页
  goHome () {
    Taro.switchTab({url: '/pages/index/index'})
  }

  // 切换全选
  toggleAll (bool) {
    const {list} = this.props.cart
    if (list.length === 0) return
    const newList = list.map(product => Object.assign({}, product, {selected: bool}))
    this.props.onChangeSelect(newList)
  }

  componentWillReceiveProps () {
    // console.log(this.props, nextProps)
  }
  componentDidMount () {
    console.log('componentDidMount')
  }
  componentWillUnmount () { }

  componentDidShow () {
    this.props.onResetCart()
    this.props.onAsyncLoadCart()
    this.props.onSetCartBadge()
    console.log('加载推荐商品')
    this.props.onAsyncLoadOffer() // 加载推荐列表
  }

  componentDidHide () { }

  render () {
    // TODO 处理非本店铺商品
    // TODO 删除商品的操作
    // TODO 处理过期商品
    const {deliveryMethod} = this.state
    const {list, disList, offerList} = this.props.cart
    const {min_orderamount} = this.props.shop
    const empty = list.length === 0 // 购物车为空
    // 总价
    const total = list
      .filter(product => product.selected === true)
      .reduce((sum, product) => sum + product.product_num * product.product.sale_price, 0) || 0
    // 全选
    const allCheck = (list.length > 0) && list.length === list
      .filter(product => product.selected === true).length
    // 是否够邮费
    // const enoughPostage = (total - min_orderamount) >= 0
    const enoughPostage = true
    // 是否展示差多少钱包邮
    // const showPostage = !empty && enoughPostage
    const showPostage = true
    // 商品列表
    const renderList =  list.map((item, index) => {
      return (
        <AtSwipeAction key={index} onClick={this.handleItemClick.bind(this, item)} options={[
          {
            text: '删除',
            style: {
              backgroundColor: '#FF4949'
            }
          }
        ]}
        >
          <CartGoodItem
            goodId={item.product_id}
            shop_id={item.shop_id}
            tags={item.product.tags}
            thumb={item.product.thumb}
            name={item.product.name}
            sales={item.product.month_sale}
            price={item.product.sale_price}
            sale_price={item.product.sale_price}
            spec_name={item.product.spec.name}
            weight={item.product.weight}
            original_price={item.product.original_price}
            product_num={parseInt(item.product_num)}
            selected={item.selected}
            onChange={this.handleChange}
            onSelect={this.handleSelect}
          />
        </AtSwipeAction>
      )
    })
    // 不可结算列表
    const renderDisList = disList.map((item, index) => {
      return (
        <CartGoodItem
          goodId={item.product_id}
          shop_id={item.shop_id}
          key={index}
          tags={item.product.tags}
          thumb={item.product.thumb}
          name={item.product.name}
          sales={item.product.month_sale}
          price={item.product.sale_price}
          sale_price={item.product.sale_price}
          spec_name={item.product.spec_name}
          weight={item.product.weight}
          original_price={item.product.original_price}
          product_num={parseInt(item.product_num)}
          selected={item.selected}
          disable
          onChange={this.handleChange}
          onSelect={this.handleSelect}
        />
      )
    })

    const renderOfferList = offerList.map((item, index) => {
      return (
        <GoodItem
          key={index}
          goodId={item.id}
          thumb={item.thumb}
          name={item.name}
          tags={item.tags}
          sales={item.month_sale}
          price={item.sale_price}
          spec_name={item.spec.name}
          weight={item.weight}
          isGroup={item.type_id === 2}
          host='cart'
        />
      )
    })

    return (
      <View className={(deliveryMethod === 'shop' && !showPostage) ? 'cart cart-postage' : 'cart'}>
        {/* 头部 配送方式 */}
        {!empty && <View className='header'>
          <AtButton
            className={'header-btn header-btn__left' + (deliveryMethod === 'shop' ? ' selected' : '')}
            onClick={this.setDeliveryMethod.bind(this, 'shop')}
          >一小时达</AtButton>
          <AtButton
            className={'header-btn header-btn__right' + (deliveryMethod === 'user' ? ' selected' : '')}
            onClick={this.setDeliveryMethod.bind(this, 'user')}
          >到店自提</AtButton>
          <View className='discount'>满36减6 满54减9</View>
        </View>}
        {/*配送方式为店铺 + 购物车不为空 + 不满足配送金额 = 显示差多少钱配送 */}
        {/* {deliveryMethod === 'shop' && !showPostage && min_orderamount && <View className='postage' onClick={this.goHome.bind(this)}>
          <Text>实付满{min_orderamount / 100}元免配送费，还差{parseFloat(( min_orderamount - total) / 100)}元，去凑单&gt;</Text>
        </View> } */}
        {/* 商品列表 */}
        <ScrollView
          className={empty ? 'empty-list' : 'list'}
          enableBackToTop
          scrollY
          scrollWithAnimation
          scrollTop='0'
        >
          {empty && <View className='empty'>
            <Image src={emptyCartPng} className='empty-img' />
            <Text className='empty-text'>您还没添加任何商品哦~</Text>
          </View> }
          {renderList}
          {/*不可结算列表*/}
          {disList.length && <View className='disable-list-header'>以下商品暂无法结算</View>}
          <View className='disable-list'>
            {renderDisList}
          </View>
          {/* 加载中*/}
          {/*{loading && <View className=''>加载中</View>}*/}
        </ScrollView>

        {/*推荐列表*/}
        {empty && <View className='offer-section'>
          <View className='section-header'>
            <Text className='name'>推荐商品</Text>
          </View>
          <ScrollView className='section-list' scrollWithAnimation scrollX>
            <View className='at-row'>
              {renderOfferList}
            </View>
          </ScrollView>
        </View>}

        {/*底部*/}
        <View className='footer'>
          <View className='info'>
            <View className='all' onClick={this.toggleAll.bind(this, !allCheck)}>
              <Image src={allCheck ? checkPng : uncheckPng} className='all-img' />
              <Text className='all-text'>全选</Text>
            </View>
            <View className='sum'>
              <View className='amount'>
                <Text className='amount-label'>合计：</Text>
                <Text className='amount-value'>￥{parseFloat(total / 100).toFixed(2)}</Text>
              </View>
              {/* <Text className='reight'>免配送费</Text> */}
            </View>
          </View>
          <AtButton className='checkout' onClick={this.goSettle.bind(this)}><Text>去结算</Text> <AtIcon value='chevron-right' size='14' color='#333333' /> </AtButton>
        </View>
      </View>
    )
  }
}

export default Cart
